package com.iflytek.elpmobile.utils.network;

import java.net.MalformedURLException;
import java.net.URL;

import com.iflytek.elpmobile.utils.Logging;
import com.simple.elpmobile.utils.network.model.NetworkStatus;
import com.simple.elpmobile.utils.network.model.NetworkStatusListener;
import com.simple.elpmobile.utils.network.model.NetworkStatusReason;
import com.simple.elpmobile.utils.network.model.Task;
import com.simple.elpmobile.utils.network.model.TaskHandle;


public abstract class AbstractTask implements TaskHandle, Task
{
	private static final String TAG = "AbstractTask";
	
	protected Object mStatusLock;
	protected boolean mNeedCancel;
	
	protected URL mURL;
	
	protected TaskInfo mNetworkInfo;
	
	protected NetworkStatusListener mStatusListener;
	
	protected AbstractTask(String url, NetworkStatusListener statusListener)
	{
		mNeedCancel = false;
		mStatusLock = new Object();
		 
		mStatusListener = statusListener;
		
		NetworkStatus status = NetworkStatus.Create;
		NetworkStatusReason reason = NetworkStatusReason.OK;
		try
		{
			mURL = new URL(url);
		} catch (MalformedURLException e) 
		{
			Logging.e(TAG, String.format("new URL error!e.getMessage:%s", e.getMessage()));
			reason = NetworkStatusReason.URLError;
			status = NetworkStatus.Fail;
		}
		
		mNetworkInfo = new TaskInfo(System.currentTimeMillis());
		mNetworkInfo.setStatus(status);
		mNetworkInfo.setReason(reason);
		
	}

	protected void onProcess(int process, NetworkStatus status, NetworkStatusReason reason)
	{
		synchronized (mStatusLock) 
		{
			mNetworkInfo.setProcess(process);
			if (NetworkStatus.NotChange != status) 			mNetworkInfo.setStatus(status);
			if (NetworkStatusReason.NotChange != reason) 	mNetworkInfo.setReason(reason);
			
			if (null != mStatusListener) mStatusListener.onProcess(mNetworkInfo);
		}
	}
	
	@Override
	public void cancelTask() 
	{
		mNeedCancel = true;
	}
}
